import { execSync as exec } from 'child_process';
import os from 'os';
import fs from 'fs';
import path from 'path';
import { createRequire } from 'module';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const require = createRequire(import.meta.url);
const information = require('../information.json');

const getDevelopers = () => {
  const preDevelopers = information.developers;
  let developers = '';
  let currentDeveloper = '';
  try {
    currentDeveloper = exec('git config user.name', {
      encoding: 'utf8',
    }).replace('\n', '');
  } catch (e) {
    console.log(e);
  }
  if (preDevelopers) {
    if (preDevelopers.split(',').includes(currentDeveloper)) {
      developers = preDevelopers;
    } else {
      developers = `${preDevelopers},${currentDeveloper}`;
    }
  } else {
    developers = currentDeveloper;
  }
  return developers;
};

const getIpAddress = () => {
  const ifaces = os.networkInterfaces();
  for (const dev in ifaces) {
    const iface = ifaces[dev];
    for (let i = 0; i < iface.length; i++) {
      const { family, address, internal, mac } = iface[i];
      if (
        family === 'IPv4' &&
        address !== '127.0.0.1' &&
        !internal &&
        mac !== '00:00:00:00:00:00'
      ) {
        return address;
      }
    }
  }
};

const writeInformation = () => {
  information.developers = getDevelopers();
  information.ipAddress = getIpAddress();
  fs.writeFileSync(
    path.resolve(__dirname, '../information.json'),
    JSON.stringify(information, null, 2),
    'utf8',
  );
};

export default writeInformation;
